<?php
# http://projects:8081/cdapp-2kt-api/api/flow_ntfm_get.php

include_once '_portal.php';

const DEF_HOUR_BEF = 4;
const DEF_HOUR_AFT = 20;
const FAKE = false;

$timestamp = timestamp();
$ip = get_client_ip();
// $fake = $ip == '127.0.0.1' ? FAKE : false;
$fake = false;

$begTime = isset($_GET['begTime']) ? $_GET['begTime'] : date('Y-m-d H', time() - 3600 * DEF_HOUR_BEF) . ':00:00';
$endTime = isset($_GET['endTime']) ? $_GET['endTime'] : date('Y-m-d H', time() + 3600 * DEF_HOUR_AFT) . ':00:00';
$history = isset($_GET['history']) ? $_GET['history'] : false;

$moment = $begTime;

# output $fake data for testing purposes

if ($fake) {
  $begHour = (int)substr($begTime, 11, 2);
  $time_length = strtotime($endTime) - strtotime($begTime);
  $begTime = ($begHour < 15 ? '2022-08-30 ' : '2022-08-29 ') . substr($begTime, 11, 8);
  $endTime = date('Y-m-d H:i:s', strtotime($begTime) + $time_length);
}

# history data

$history_colunm = $history ? ', `history`, `sector`, `mode`, `details`' : '';

$sql = "SELECT `moment`, `content`{$history_colunm} FROM `2kt_flow_record` WHERE `moment` >= '{$begTime}' AND `moment` < '{$endTime}' ORDER BY `moment` ASC";

$tags = (isset($_GET['tag']) ? $_GET['tag'] : 0) > 0 ? get_param('flowTags') : null;

$result = exec_sql($sql);

# version added @2022/12/06
// const PARAM_NAME_VERSION = 'flowDataVersion';
// $version = get_param(PARAM_NAME_VERSION)['value'];
// if ($fake) {
//   $version = date('Y-m-d H:i:s');
// }

$version = param('NTFM_TMA_TIMESTAMP_RECIVE');
$freshness = (timestamp() - $version) / 1000;

$output = [];
$output['duration'] = 0;
$output['count'] = 0;
$output['begTime'] = $moment;
$output['history'] = $history;
$output['version'] = $version;
$output['reference'] = date('Y-m-d H:i:s');
$output['freshness'] = $freshness;
$output['sql'] = $sql;
$tags ? $output['tags'] = $tags : null;
$output['rawData'] = [];
// 流量限制信息： 从 params 表中读取 FLOW_LIMITS_TMA 项目
$output['flowLimits'] = param('FLOW_LIMITS_TMA');

if ($history) {
  $output['rawDataOld'] = [];
  $output['seats'] = [];
  $output['details'] = [];
  $output['mode'] = [];
}

if ($result && count($result) > 0) {
  $result = query_parse($result);
  $output['begTime'] = $fake ? $moment : $result[0]['moment'];
  $output['count'] = count($result);
  foreach ($result as $line) {
    $output['rawData'][] = $line['content'];
    if ($history) {
      $output['rawDataOld'][] = $line['history'];
      $output['sector'][] = $line['sector'];
      $output['details'][] = $line['details'];
      $output['mode'][] = $line['mode'];
    }
  }
}

$output['duration'] = timestamp() - $timestamp . 'ms';
$output['isStoped'] = (get_variable('STOP_ALL_NETWORK') === 1 || get_variable('STOP_NTFM') === 1) && !$fake;

output($output);